from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QPixmap
from PyQt5 import QtGui, uic
import charts
from charts.funcs import *
import math
import sys
import os
from pathlib import Path
import PyQt5


os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = os.fspath(
    Path(PyQt5.__file__).resolve().parent / "Qt5" / "plugins"
)


class Y:
    def __init__(self, e):
        self.e = e

    def gen(self, x):
        return eval(self.e.format(x=x))


class App(QMainWindow):
    def __init__(self):
        super(App, self).__init__()
        # self.ui = main_ui.Ui_MainWindow()
        # self.ui.setupUi(self)
        self.folder = 'files'
        self.ui_folder = os.path.join(self.folder, 'ui')
        self.img_folder = os.path.join(self.folder, 'img')
        uic.loadUi(os.path.join(self.ui_folder, 'main.ui'), self)
        self.setWindowTitle('pycharts')
        self.btn_generate.clicked.connect(self.generate_image)
        self.log('Функции выражения:\ncube_root - квадратный корень\nmodule - модуль\n'
                 '** - возведение в квадрат\n/ - деление\n* - умножение\n% - остаток от деления\n'
                 'Пример: cube_root(x - 2) + 3')
        self.filename = 'out.png'
        self.load_image(os.path.join(self.img_folder, 'file-not-found.jpg'))

    def log(self, text, end='\n'):
        self.text_out.setText(self.text_out.toPlainText()+str(text)+end)

    def generate_image(self):
        try:
            y = Y(self.lineedit_eval.text())
            step = float(self.lineedit_step.text())
            iters = int(self.lineedit_iters.text())
            size = int(self.lineedit_size.text())
            back = self.check_back.checkState()
            chart = charts.Chart(y.gen, step=step, iters=iters, name=self.filename, backward=back, rad=size)
            chart.generate()
            self.load_image(self.filename)
            self.text_out.clear()
            self.log(f'Успешно! Сохранено в "{self.filename}".')
        except Exception as e:
            self.log(str(e))

    def load_image(self, file_name):
        pixmap = QPixmap(file_name)
        self.image.setPixmap(pixmap)
        self.image.resize(191, 191)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = App()
    window.show()
    sys.exit(app.exec_())
